// import { Trans } from '@lingui/react'
import { GlobalFooter } from 'ant-design-pro'
import { BackTop, Drawer, Layout, notification } from 'antd'
import { MyLayout } from 'components'
import { connect } from 'dva'
import { enquireScreen, unenquireScreen } from 'enquire-js'
import PropTypes from 'prop-types'
import React, { Fragment, PureComponent } from 'react'
import withRouter from 'umi/withRouter'
import { config, langFromPath, pathMatchRegexp } from 'utils'
import Error from '../pages/404'
import styles from './PrimaryLayout.less'
const { Content } = Layout
const { Header, Bread, Sider } = MyLayout

//
@withRouter
@connect(({ socket, app, loading }) => {
  const {
    user,
    routeList,
    collapsed,
    permissions,
    notifications,
    isMobile,
  } = app
  return {
    socket,
    user,
    routeList,
    collapsed,
    permissions,
    notifications,
    isMobile,
    loading,
  }
})
class PrimaryLayout extends PureComponent {
  state = {}

  inited = 0 //0-没有初始化 1-正在初始化 2-初始化成功

  initsocket() {
    const { dispatch, socket } = this.props
    const { windowToken } = socket
    if (this.inited != 0) return
    this.inited = 1
    //
    console.log('init socket')
    //
    let timer
    var ws = new WebSocket(
      'ws://langyuenbiot.leanapp.cn/chat/' + //localhost:3000
        sessionStorage.getItem('mr-ly-sessionToken-session') +
        '/' +
        windowToken
    )

    dispatch({ type: 'socket/updateState', payload: { subSocket: ws } })

    ws.onopen = () => {
      this.inited = 2
      console.log('打开端口')
    }
    ws.onmessage = evt => {
      var received_msg = evt.data
      console.log('receivedmsg:' + received_msg)
      if (received_msg.indexOf('error:') != -1) {
        if (received_msg.indexOf('错误码:5003') != -1) {
          //权限不足 不再继续重连
          this.inited = 5 //状态设置为已开启，但权限不足，所有直接关闭ws即可
          //5 为永远不再开启
          dispatch({ type: 'socket/closeWs' })
        }
        return
      }
      var data = JSON.parse(received_msg)
      if (data && data.type) {
        if (data.type == 'Notify') {
          var descript = ''
          for (let index in data.data) {
            var item = data.data[index]
            switch (item.type) {
              case 'User':
                descript += `${item.params.role}(${item.params.username})`
                break
              case 'Device':
                descript += `设备:${item.params.DeviceName} `
                break
              case 'Project':
                // descript += `设备:${item.params.DeviceName} `
                break
              case 'Words':
                descript += item.words
                break
            }
          }
          notification.open({
            message: '您收到一条新消息！',
            description: descript,
          })
          //
          dispatch({ type: 'app/getUnreadMsg' })
        } else if (data.type == 'Report') {
          dispatch({ type: 'userDetail/onReceiveReport', payload: data.msg })
        } else if (data.type == 'Action') {
          notification.error({
            message: '您收到一条新消息！',
            description: data.msg,
          })
          dispatch({ type: 'loras/query' })
        } else if (data.type == 'Action_S') {
          notification.success({
            message: '您收到一条新消息！',
            description: data.msg,
          })
          dispatch({ type: 'loras/query' })
        } else if (data.type == 'Mission_R') {
          dispatch({ type: 'cmdlist/onGetResponse', payload: data.msg })
        }
      }
    }
    timer = setInterval(() => {
      ws.send(1)
    }, 30000)
    ws.onclose = () => {
      console.log('连接已关闭...')
      dispatch({
        type: 'socket/updateState',
        payload: { subSocket: undefined },
      })
      clearInterval(timer)
      if (this.inited != 5) {
        setTimeout(() => {
          this.inited = 0
          this.initsocket()
        }, 3000)
      }
    }
    this.timer = timer
    window.onbeforeunload = () => {
      ws.close()
      // dispatch({ type: 'app/closeWs' })
    }
  }

  componentWillReceiveProps(nextprops) {
    const { user, socket } = this.props
    const { subSocket, windowToken } = socket
    var token = sessionStorage.getItem('mr-ly-sessionToken-session')
    if (user && user.username && token && windowToken) {
      if (!subSocket) {
        this.initsocket()
      }
    }
  }

  componentDidMount() {
    const { dispatch } = this.props
    this.enquireHandler = enquireScreen(mobile => {
      if (this.props.isMobile != mobile) {
        dispatch({
          type: 'app/setMobile',
          payload: mobile,
        })
      }
    })
    this.resizelistener = () => {
      dispatch({
        type: 'app/updateState',
        payload: {
          clientWidth: document.body.clientWidth,
          clientHeight: document.body.clientHeight,
        },
      })
    }
    window.addEventListener('resize', this.resizelistener, false)
  }
  shouldComponentUpdate(nextprops, nextstate) {
    // const { } = this.props
    const {
      user,
      routeList,
      collapsed,
      permissions,
      notifications,
      isMobile,
      location,
      children,
    } = this.props
    //!(nextprops.socket.windowToken != this.props.socket.windowToken || nextprops.socket.subSocket != this.props.socket.subSocket)
    return (
      user != nextprops.user ||
      routeList != nextprops.routeList ||
      collapsed != nextprops.collapsed ||
      permissions != nextprops.permissions ||
      notifications != nextprops.notifications ||
      isMobile !== nextprops.isMobile ||
      location !== nextprops.location ||
      children != nextprops.children
    )
  }

  componentWillUnmount() {
    unenquireScreen(this.enquireHandler)
    clearInterval(this.timer)
    window.removeEventListener('resize', this.resizelistener)
  }

  onCollapseChange = collapsed => {
    this.props.dispatch({
      type: 'app/handleCollapseChange',
      payload: collapsed,
    })
  }

  render() {
    const {
      user,
      routeList,
      collapsed,
      permissions,
      notifications,
      isMobile,
      location,
      dispatch,
      children,
    } = this.props
    // if (!app) return null;
    // const {
    //   user,
    //   routeList,
    //   collapsed,
    //   permissions,
    //   notifications,
    //   isMobile,
    // } = app
    // const { isMobile } = this.state
    const { onCollapseChange } = this

    // Localized route name.

    const lang = langFromPath(location.pathname)
    const newRouteList =
      lang != 'en'
        ? routeList.map(item => {
            const { name, ...other } = item
            return {
              ...other,
              name: (item[lang] || {}).name || name,
            }
          })
        : routeList

    // Find a route that matches the pathname.
    const currentRoute = newRouteList.find(
      _ => _.route && pathMatchRegexp(_.route, location.pathname)
    )

    // Query whether you have permission to enter this page
    const hasPermission = currentRoute
      ? permissions.visit.includes(currentRoute.id)
      : false

    // MenuParentId is equal to -1 is not a available menu.
    const menus = newRouteList.filter(_ => _.menuParentId != '-1')

    const headerProps = {
      menus,
      collapsed,
      notifications,
      onCollapseChange,
      avatar: user.avatar,
      username: user.username,
      fixed: config.fixedHeader,
      onDelNotify: index => {
        dispatch({
          type: 'app/clearUnread',
          payload: { msg: notifications[index] },
        }).then(() => {
          dispatch({ type: 'app/getUnreadMsg' })
        })
      },
      onAllNotificationsRead: e => {
        dispatch({ type: 'app/clearAllunread' }).then(() => {
          dispatch({ type: 'app/getUnreadMsg' })
        })
      },
      onSignOut: () => {
        dispatch({ type: 'app/signOut' }).then(() => {
          dispatch({ type: 'devices/clearstore' })
          dispatch({ type: 'userDetail/clearstore' })
        })
      },
    }
    let theme = 'light'
    if (user && user.permissions && user.permissions.role) {
      theme = user.permissions.role == 'admin' ? 'dark' : 'light'
    }
    const siderProps = {
      theme,
      menus,
      isMobile,
      collapsed,
      onCollapseChange,
      onThemeChange(theme) {
        dispatch({
          type: 'app/handleThemeChange',
          payload: theme,
        })
      },
    }
    const isdashboard = pathMatchRegexp('/dashboard', location.pathname)
    // const emptyitem = () => {
    //   <Empty
    //     image="http://lc-rohmehlw.cn-n1.lcfile.com/ebe1c69d8a473f5fb2ba.png"//{<div></div>}
    //     description={
    //       <div style={{ textAlign: 'center' }}>
    //         {/* <Icon type="smile" style={{ fontSize: 20 }} /> */}
    //         <Trans>Data Not Found</Trans>
    //       </div>
    //     }
    //   />
    // }
    return (
      <Fragment>
        <Layout>
          {isMobile ? (
            <Drawer
              maskClosable
              closable={false}
              onClose={onCollapseChange.bind(this, !collapsed)}
              visible={!collapsed}
              placement="left"
              width={250}
              bodyStyle={{
                padding: 0,
                height: '100%',
                overflow: 'hidden',
              }}
              style={{
                padding: 0,
                height: '100vh',
                overflow: 'hidden',
              }}
            >
              <Sider {...siderProps} collapsed={false} />
            </Drawer>
          ) : (
            <Sider {...siderProps} />
          )}
          <div
            className={styles.container}
            style={{ paddingTop: config.fixedHeader ? 72 : 0 }}
            id="primaryLayout"
          >
            <Header {...headerProps} />
            {/* <ConfigProvider renderEmpty={emptyitem}> */}
            <Content
              className={styles.content}
              style={isdashboard && { padding: '0px', margin: '0px' }}
            >
              {!isdashboard && <Bread routeList={newRouteList} />}
              {hasPermission ? children : <Error />}
            </Content>
            {/* </ConfigProvider > */}
            {/* <Chat user={user} massageList={massageList} /> */}
            <BackTop
              className={styles.backTop}
              target={() => document.querySelector('#primaryLayout')}
            />
            <GlobalFooter
              className={styles.footer}
              copyright={config.copyright}
            />
          </div>
        </Layout>
      </Fragment>
    )
  }
}

PrimaryLayout.propTypes = {
  children: PropTypes.element.isRequired,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  app: PropTypes.object,
  loading: PropTypes.object,
}

export default PrimaryLayout

// var ws = new WebSocket(
//   'ws://localhost:3000/chat/' + //langyuenbiot.leanapp.cn
//   sessionStorage.getItem('mr-ly-sessionToken-session') +
//   '/' +
//   windowToken
// )
// dispatch({ type: 'app/updateState', payload: { subSocket: ws } })
// ws.onopen = () => {
//   this.inited = 2
//   console.log('打开端口')
// }
// ws.onmessage = evt => {
//   var received_msg = evt.data
//   console.log('receivedmsg:' + received_msg)
//   if (received_msg.indexOf('error:') != -1) {
//     if (received_msg.indexOf('错误码:5003') != -1) {
//       //权限不足 不再继续重连
//     } else {
//       this.inited = 0
//       setTimeout(() => {
//         dispatch({ type: 'app/closeWs' })
//       }, 5000)
//     }
//     return
//   }
//   var data = JSON.parse(received_msg)
//   if (data && data.type) {
//     if (data.type == 'Notify') {
//       var descript = ''
//       for (let index in data.data) {
//         var item = data.data[index]
//         switch (item.type) {
//           case 'User':
//             descript += `${item.params.role}(${item.params.username})`
//             break
//           case 'Device':
//             descript += `设备:${item.params.DeviceName} `
//             break
//           case 'Project':
//             // descript += `设备:${item.params.DeviceName} `
//             break
//           case 'Words':
//             descript += item.words
//             break
//         }
//       }
//       notification.open({
//         message: '您收到一条新消息！',
//         description: descript,
//       })
//       //
//       dispatch({ type: 'app/getUnreadMsg' })
//     } else {
//       //聊天消息
//     }
//   }
// }
// ws.onclose = () => {
//   if (this.inited != 0) {
//     // this.inited = 0
//     console.log('连接已关闭...')
//     // dispatch({ type: 'app/updateState', payload: { subSocket: undefined } })

//     // this.initsocket()
//   }
// }
// window.onbeforeunload = () => {
//   ws.close()
// }
